package com.sunrise.gateway.shiro.session;

import com.dap.exception.BusinessException;
import com.sunrise.gateway.commons.Constants;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;

public class RedisSessionDAO extends AbstractSessionDAO {

    private static Logger logger = LoggerFactory.getLogger(RedisSessionDAO.class);
    /**
     * shiro-redis的session对象前缀
     */
    private SessionRepositoryInterface sessionRepository;


    public void update(Session session) throws UnknownSessionException {
        this.saveSession(session);
    }


    /**
     * save session
     * 
     * @param session
     * @throws UnknownSessionException
     */
    private void saveSession(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            logger.error("session or session id is null");
            return;
        }
        this.sessionRepository.set(session.getId().toString(), session);
    }


    public void delete(Session session) {
        if (session == null || session.getId() == null) {
            logger.error("session or session id is null");
            return;
        }
        sessionRepository.del(session.getId().toString());
    }


    public Collection<Session> getActiveSessions() {
        return null;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            logger.error("session id is null");
            return null;
        }
        try {
            Session session = sessionRepository.get(sessionId.toString());
            return session;
        }catch(UnknownSessionException unknownSessionException){
            logger.error("", unknownSessionException);
            throw new BusinessException(Constants.USER_SESSION_INVALID, unknownSessionException);
        } catch (Exception e) {
            logger.error("", e);
            throw new BusinessException(com.dap.commons.Constants.ResponseCode.SYS_ERROR, e);
        }
    }


    public SessionRepositoryInterface getSessionRepository() {
        return sessionRepository;
    }


    public void setSessionRepository(SessionRepositoryInterface sessionRepository) {
        this.sessionRepository = sessionRepository;
    }


}

